#include "ZeroMessage.h"

ZeroMessage::ZeroMessage()
{
	mMutex = new ZeroMutex();
	mMsg = new int[128];
	mMsgHead = 0;
	mMsgTail = 0;
	mMsgCapacity = 128;
}

ZeroMessage::~ZeroMessage()
{
	if (mMsg)
		delete [] mMsg;
	if (mMutex)
		delete [] mMutex;
}

int ZeroMessage::getMessage()
{
	int msg = 0;
	mMutex->lock();
	if (mMsgHead != mMsgTail) {
		msg = mMsg[mMsgHead];
		mMsgHead = (mMsgHead + 1) % mMsgCapacity;
	}
	mMutex->unlock();
	return msg;
}

void ZeroMessage::postMessage(int msg)
{
	mMutex->lock();
	mMsg[mMsgTail] = msg;
	mMsgTail = (mMsgTail + 1) % mMsgCapacity;
	if (mMsgTail == mMsgHead) { // full...
		int *newMsg = new int[mMsgCapacity + 128];
		for (int i = 0;i < mMsgCapacity;i++) {
			newMsg[i] = mMsg[mMsgHead];
			mMsgHead = (mMsgHead + 1) % mMsgCapacity;
		}
		mMsgHead = 0;
		mMsgTail = mMsgCapacity;
		mMsgCapacity = mMsgCapacity + 128;
	}
	mMutex->unlock();
}

bool ZeroMessage::isEmpty()
{
	bool result;
	mMutex->lock();
	result = (mMsgHead == mMsgTail);
	mMutex->unlock();
	return result;
}
